<template>
  <div id="patrolTaskEdit">
    <GoBack content="巡检计划" :backUrl="backUrl" />
    <div class="bodyContent">
      <!-- 三目运算判断 -->
      <vxe-toolbar perfect style="height: 16%">
        <template #buttons>
          <el-form ref="taskFormRef" :model="planForm" label-width="140px" class="form-input-m" :inline-message="true" :disabled="isDisabled()">
            <el-row>
              <el-col :span="8">
                <el-form-item prop="code" label="计划编号">
                  <el-input v-model="planForm.code" type="text" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="name" label="计划名称">
                  <el-input v-model="planForm.name" type="text" placeholder="请输入计划名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="type" label="检测方式">
                  <el-select v-model="planForm.type" filterable placeholder="检测方式" style="width: 200px">
                    <el-option v-for="ctype in ctypeList" :key="ctype.code" :label="ctype.name" :value="ctype.code"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="type" label="计划类型">
                  <el-radio-group v-model="planForm.planType">
                    <el-radio :label="typeObj.code" v-for="(typeObj, index) in planTypeList" :key="index" @change="(val) => planTypeChange(val, typeObj)">
                      {{ typeObj ? typeObj.name : typeObj.name }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="开始时间">
                  <el-date-picker style="width: 200px" v-model="planForm.beginTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结束时间">
                  <el-date-picker style="width: 200px" v-model="planForm.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="planForm.planType == '1'">
                <el-form-item label="固定时间">
                  <el-date-picker style="width: 200px" v-model="planForm.nextTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="planForm.planType == '2'">
                <el-form-item label="表达式">
                  <el-input v-model="planForm.cron" type="text">
                    <template #suffix>
                      <i class="vxe-icon-setting-fill" @click="getCron()"></i>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="planForm.planType == '2'">
                <el-form-item label="表达说明">
                  <el-input v-model="planForm.cronDesc" type="text" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="planForm.planType == '2'">
                <el-form-item label="下次时间">
                  <el-date-picker style="width: 200px" v-model="planForm.nextTime" type="datetime" :disabled="planForm.planType == '2'" />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="planForm.planType == '2'">
                <el-form-item label="未来五次">
                  <span v-for="item in dateList" :key="item" style="color: red">{{ item }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="执行人" :required="true">
                  <VxePulldownSelection
                      v-enterNextInput
                      :url="'/api/user/getUserInfoList'"
                      @confirmClick="dropPullDownConfirm"
                      :tableColumn="[
                      { field: 'username', title: '编号', width: '60px' },
                      { field: 'realname', title: '姓名' }
                    ]"
                      :aimKeys="[{ aimKey: 'handler', rowKey: 'username' }]"
                      :displayTexts="['realname']"
                      :displayTextObj="planForm.handler ? planForm.handler : ''"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </vxe-toolbar>

      <div class="contentDiv" style="height: 83%">
        <el-container>
          <el-aside width="55%">
            <el-divider content-position="left">
              设备信息
              <el-button size="small" type="success" :disabled="isDisabled()" class="add-btn" @click="showAddEquipment">添加设备 </el-button>
            </el-divider>
            <el-dialog title="选择设备" v-model="checkEquipmentShow" :show-close="false" :modal-append-to-body="false" :close-on-click-modal="false" width="900px">
              <SelectEquipment ref="sltEquipmentRef"></SelectEquipment>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmEquipment">确定</el-button>
                <el-button @click="closeEquipmentDialog">取消</el-button>
              </div>
            </el-dialog>

            <div style="height: calc(100% - 110px)">
              <vxe-table class="mb10" border ref="equipmentTableRef" :data="planForm.patrolPlanEqList" :row-config="{ isCurrent: true, isHover: true, useKey: true, keyField: 'eqId' }" :column-config="{ resizable: true }" @current-change="clickPatrolTaskEqSelect" resizable show-overflow height="auto">
                <vxe-column type="seq" width="30" title=""></vxe-column>
                <vxe-column field="equiptCode" title="设备编号" align="center" show-overflow-tooltip></vxe-column>
                <vxe-column field="equiptName" title="设备名称" align="center"></vxe-column>
                <vxe-column field="specification" title="规格型号" align="center"></vxe-column>
                <vxe-column title="巡检内容" align="center" width="150">
                  <template #default="{ row }">
                    <span>
                      <el-tag v-for="(item, index) in row.patrolPlanEqStList" :key="index">{{ item.standardName }}</el-tag>
                    </span>
                  </template>
                </vxe-column>
                <vxe-column field="equiptTypeName" title="设备类型名称" align="center"></vxe-column>
                <vxe-column field="right" label="操作" width="110" align="center">
                  <template #default="{ row }">
                    <vxe-button size="small" status="danger" icon="vxe-icon-delete" content="删除" :disabled="isDisabled()" @click="deleteEquipment"></vxe-button>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
          </el-aside>
          <el-main>
            <el-divider content-position="left">
              巡检内容
              <el-button size="small" type="success" class="add-btn" :disabled="isDisabled()" @click="showAddPatrolStandard">添加巡检标准 </el-button>
            </el-divider>
            <el-dialog title="选择巡检标准" v-model="checkPatrolStandardShow" :show-close="false" :modal-append-to-body="false" :close-on-click-modal="false" width="900px">
              <SelectPatrolStandard ref="sltPatrolStandardRef"></SelectPatrolStandard>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmPatrolStandard">确定</el-button>
                <el-button @click="closeItemDialog">取消</el-button>
              </div>
            </el-dialog>
            <div style="height: calc(100% - 110px)">
              <vxe-table class="mb10" border ref="itemTable" :data="curSeltIndex > -1 ? planForm.patrolPlanEqList[curSeltIndex].patrolPlanEqStList : []" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source height="auto">
                <vxe-column field="standardCode" title="巡检编号" align="center"></vxe-column>
                <vxe-column field="standardName" title="巡检名称" align="center"></vxe-column>
                <vxe-column field="standardType" title="巡检类型" align="center"></vxe-column>
                <vxe-column field="purpose" title="巡检目的" align="center"></vxe-column>
              </vxe-table>
            </div>
            <div style="width: 100%; text-align: right; margin-top: 10px; padding-right: 10px; box-sizing: border-box">
              <el-button type="primary" v-loading="submiting" :disabled="isDisabled()" size="small" @click="saveForm()">提交 </el-button>
            </div>
          </el-main>
        </el-container>

        <el-dialog v-model="state.cronPopover" width="800px" height="400px" align-center :close-on-click-modal="false" :close-on-press-escape="false">
          <Cron @change="changeCron" v-model:value="planForm.cron" />
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import GoBack from '@/components/GoBack.vue'; //返回组件
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import SelectEquipment from '@/components/SelectEquipment.vue';
import SelectPatrolStandard from '@/components/SelectPatrolStandardAndItem.vue';
import { IsEmpty, notifyMessage, notifyType } from '@/utils/common';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';

import Cron from '@/components/Cron.vue'; //返回组件

let { proxy }: any = getCurrentInstance();

let radio = ref(1);
let backUrl = ref('');
let checkEquipmentShow = ref(false);
let checkPatrolStandardShow = ref(false);
let cronPopover = ref(false);
let equipmentTableRef = ref(null);
let sltPatrolStandardRef = ref(null);
let ctypeList: any = reactive([]);
let userList: any = reactive([]);
let dateList: any = reactive([]);

let sltPatrolPlanEq = reactive({});
let curSeltIndex = ref(-1);
let submiting = ref(false);
let sltEquipmentRef = ref(null);
let planTypeList: any = reactive([
  { name: '单次', code: '1' },
  { name: '多次', code: '2' }
]); //选择字典

let planForm = reactive({
  id: '',
  name: '',
  code: '',
  type: '',
  typeDesc: '',
  status: '',
  handler:'',
  beginTime: '',
  nextTime: '',
  cron: '',
  cronDesc: '',
  orgId: '',
  patrolPlanEqList: [],
  planType: '1'
});
const state = reactive({
  cronPopover: false
});
function getCron() {
  state.cronPopover = true;
}
const changeCron = (val) => {
  if (typeof val !== 'string') return false;
  state.cronPopover = false;
  planForm.cron = val;
  closeCron(0);
};
onMounted(() => {
  getCtypeList();
  planForm.id = proxy.$route.query.id ? proxy.$route.query.id.toString() : '';
  backUrl = proxy.$route.query.url.toString();
  if (planForm.id) {
    getPatrolPlanById();
  }
});

function closeCron(flag) {;
  if (flag === 0) {
    dateList.length = 0;
    const url = '/api/eq/eqMaintainPlan/validateCron';
    proxy.$http
      .get(url, { params: { cron: planForm.cron } })
      .then((res: any) => {
        if (res.status.code !== 1) {
          VxeMessage('修改失败', VxeNotifyType.error);
        } else {
          planForm.cronDesc = res.data.des;
          dateList.push(...res.data.dateList);
          planForm.nextTime = dateList[0];
        }
      })
      .catch((err) => {
        console.log(err);

        VxeMessage('修改失败', VxeNotifyType.error);
      });
    //this.showCronBox = false;
  } else {
    //this.showCronBox = false;
  }
}
//获取检测方式数据字典
function getCtypeList() {
  ctypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'ctype' } })
    .then((res: any) => {
      Object.assign(ctypeList, res.data);
    })
    .catch((err: any) => {});
}
function planTypeChange(val: any, item: any) {
  if (val == '1') {
  } else if (val == '2') {
  }
}

/**下拉选中 */
function dropPullDownConfirm(e) {
  e.aimKeys.forEach((m) => {
    planForm[m.aimKey] = e.row[m.rowKey];
  });
}

function getTypeDesc(scope, options) {
  for (const item of options) {
    if (scope === item.id) {
      return item.name;
    }
  }
}

//获取修改所有页面信息
function getPatrolPlanById() {
  const url = '/api/eq/patrolPlan/findPatrolPlanById';
  proxy.$http
    .get(url, { params: { id: planForm.id } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        Object.assign(planForm, res.data);
        if (planForm.patrolPlanEqList && planForm.patrolPlanEqList.length > 0) {
          equipmentTableRef.value.setCurrentRow(planForm.patrolPlanEqList[0]);
          sltPatrolPlanEq = planForm.patrolPlanEqList[0];
          curSeltIndex.value = 0;
        }
      }
    })
    .catch((err) => {
      proxy.$alert(err, '提示');
    });
}

function clickPatrolTaskEqSelect({ row, rowIndex }) {
  curSeltIndex.value = rowIndex;
  sltPatrolPlanEq = row;
  sltPatrolStandardRef.value?.setSltPatrolStandardList(row.patrolPlanEqStItList);
}

function showAddEquipment() {
  sltEquipmentRef.value?.setPatrolTaskEqList(planForm.patrolPlanEqList);
  checkEquipmentShow.value = true;
}

function showAddPatrolStandard() {
  if (!sltPatrolPlanEq.eqId) {
    VxeMessage('先选择设备', VxeNotifyType.error);
    return;
  }
  const sltPatrolStandardList = [];
  if (sltPatrolPlanEq.patrolPlanEqStList) {
    for (const item of sltPatrolPlanEq.patrolPlanEqStList) {
      const patrolStandard = {
        id: item.standardId
      };
      sltPatrolStandardList.push(patrolStandard);
    }
  }
  sltPatrolStandardRef.value?.setSltPatrolStandardList(sltPatrolStandardList);
  checkPatrolStandardShow.value = true;
}

function confirmEquipment() {
  const sltEquipmentList = sltEquipmentRef.value.checkedRowList;
  const patrolPlanEqList = [];
  for (const item of sltEquipmentList) {
    const sm = planForm.patrolPlanEqList.some((p: any) => p.eqId === item.id);
    if (sm) {
      patrolPlanEqList.push(planForm.patrolPlanEqList.find((p: any) => p.eqId === item.id));
    } else {
      const patrolTaskEq = {
        id: '',
        planId: planForm.id,
        eqId: item.id,
        equiptName: item.equiptName,
        specification: item.specification,
        amount: item.amount,
        supplierName: item.supplierName,
        manuName: item.manuName,
        equiptCode: item.equiptCode,
        patrolPlanEqStList: [],
        patrolPlanEqStItList: []
      };
      patrolPlanEqList.push(patrolTaskEq);
    }
  }
  planForm.patrolPlanEqList = patrolPlanEqList;
  if (planForm.patrolPlanEqList && planForm.patrolPlanEqList.length > 0) {
    equipmentTableRef.value.setCurrentRow(planForm.patrolPlanEqList[0]);
    sltPatrolPlanEq = planForm.patrolPlanEqList[0];
    curSeltIndex.value = 0;
  }
  checkEquipmentShow.value = false;
}

function deleteEquipment() {
  const $xTable = proxy.$refs.equipmentTableRef as any;
  let selectRows = $xTable.getCheckboxRecords();
  proxy.$XModal.confirm('您确定要删除吗？').then((type) => {
    if (type === 'confirm') {
      planForm.patrolPlanEqList.splice(curSeltIndex.value, 1);
      //设置选中第一行
      if (planForm.patrolPlanEqList && planForm.patrolPlanEqList.length > 0) {
        const current: any = proxy.$refs.equipmentTableRef;
        current.setCurrentRow(planForm.patrolPlanEqList[0]);
        sltPatrolPlanEq = planForm.patrolPlanEqList[0];
        curSeltIndex.value = 0;
      } else {
        curSeltIndex.value = -1;
        Object.assign(sltPatrolPlanEq, null);
      }
    }

  })
}

//巡检标准-确定
function confirmPatrolStandard() {
  const sltPatrolStandardList = sltPatrolStandardRef.value.sltPatrolStandardList;
  const patrolPlanEqStList = [];
  const patrolPlanEqStItList = [];

  for (const standard of sltPatrolStandardList) {
    const sm = sltPatrolPlanEq.patrolPlanEqStList.some((p: any) => p.standardId === standard.id);
    if (sm) {
      patrolPlanEqStList.push(sltPatrolPlanEq.patrolPlanEqStList.find((p: any) => p.standardId === standard.id));
    } else {
      const patrolTaskEqSt = {
        id: '',
        planId: planForm.id,
        planEqId: sltPatrolPlanEq.id,
        eqId: sltPatrolPlanEq.eqId,
        standardId: standard.id,
        standardCode: standard.standardCode,
        standardName: standard.standardName,
        standardType: standard.standardType,
        purpose: standard.purpose
      };
      patrolPlanEqStList.push(patrolTaskEqSt);
    }
    for (const item of standard.pollingProjectList) {
      const eqStIt = sltPatrolPlanEq.patrolPlanEqStItList.some((p: any) => p.standardItemId === item.id);
      if (eqStIt) {
        patrolPlanEqStItList.push(sltPatrolPlanEq.patrolPlanEqStItList.find((p: any) => p.standardItemId === item.id));
      } else {
        const patrolTaskEqStIt = {
          id: '',
          planId: planForm.id,
          planEqId: sltPatrolPlanEq.id,
          eqId: sltPatrolPlanEq.eqId,
          standardId: standard.id,
          standardName: standard.standardName,
          standardItemId: item.id,
          projectCode: item.projectCode,
          projectName: item.projectName,
          projectType: item.projectType,
          normalValue: item.normalValue,
          exceptValue: item.exceptValue,
          defValue: item.defValue,
          maxValue: item.maxValue,
          mixValue: item.mixValue,
          seq: item.seq,
          checkResultTest: item.checkResultTest,
          checkResultTestList: []
        };
        patrolPlanEqStItList.push(patrolTaskEqStIt);
      }
    }
  }
  sltPatrolPlanEq.patrolPlanEqStList = patrolPlanEqStList;
  sltPatrolPlanEq.patrolPlanEqStItList = patrolPlanEqStItList;

  checkPatrolStandardShow.value = false;
}

function closeItemDialog() {
  checkPatrolStandardShow.value = false;
}

function closeEquipmentDialog() {
  checkEquipmentShow.value = false;
}

function saveForm() {
  submiting.value = true;
  planForm.status = '5';
  let url = '';
  if (planForm.id) {
    url = '/api/eq/patrolPlan/editPatrolPlan';
  } else {
    url = '/api/eq/patrolPlan/addPatrolPlan';
  }
  proxy.$http
    .post(url, planForm)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('提交成功', VxeNotifyType.success);
        planForm.id = res.data.id;
        planForm.code = res.data.code;
        getPatrolPlanById();
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      submiting.value = false;
    })
    .catch((err) => {
      submiting.value = false;
    });
}

function inputBlurHandler(scope) {
  if (scope.checkResultTest) {
    scope.checkResult = scope.checkResultTest;
    const maxValue = parseFloat(scope.maxValue);
    const mixValue = parseFloat(scope.mixValue);
    const checkResult = parseFloat(scope.checkResult);
    if (checkResult <= maxValue && checkResult >= mixValue) {
      scope.isNormal = '正常';
    } else {
      scope.isNormal = '异常';
    }
  } else {
    scope.checkResult = '';
    scope.checkResultTest = '';
    scope.isNormal = '';
  }
}

function changRradioItem(scope, item) {
  item === scope.checkResultTest ? (scope.checkResultTest = '') : (scope.checkResultTest = item);
  scope.checkResult = scope.checkResultTest;
  if (scope.checkResultTest === '') {
    scope.isNormal = '';
  } else {
    const i = scope.normalValue.indexOf(scope.checkResultTest);
    if (i >= 0) {
      scope.isNormal = '正常';
    } else {
      const j = scope.exceptValue.indexOf(scope.checkResultTest);
      if (j >= 0) {
        scope.isNormal = '异常';
      } else {
        scope.isNormal = '';
      }
    }
  }
}

function changCheckbox(scope) {
  if (scope.checkResultTestList && scope.checkResultTestList.length > 0) {
    scope.checkResult = scope.checkResultTestList.join(';');
    scope.checkResultTest = scope.checkResultTestList.join(';');
    const ycList = scope.exceptValue.split(';');
    let isHve = false;
    for (const yc of ycList) {
      const i = scope.checkResultTest.indexOf(yc);
      if (i >= 0) {
        isHve = true;
      }
    }
    if (isHve) {
      scope.isNormal = '异常';
    } else {
      scope.isNormal = '正常';
    }
  } else {
    scope.checkResult = '';
    scope.checkResultTest = '';
    scope.isNormal = '';
  }
}

function isDisabled() {
  return (planForm.status == '0' ||planForm.status == '')? false: true;
}
</script>
<style lang="scss" scoped>
#patrolTaskEdit {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .el-form {
      margin-top: 10px;
    }

    .contentDiv {
      background-color: $base-white;
      height: calc(100% - 95px);
      margin-top: 10px;

      .el-container {
        .mb10 {
          margin-bottom: 10px;
        }

        .add-btn {
          padding: 5px;
          margin-left: 10px;
        }

        .el-aside {
          background-color: $base-white !important;
          margin: 0;
          padding: 0 10px;
        }

        .el-main {
          background-color: $base-white;

          padding: 0 10px;

          .el-checkbox-group .check-row-inline {
            height: 10px;
            line-height: 30px;
            padding: 0 5px 0 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;

            .el-checkbox {
              width: 70px !important;
              margin-bottom: 2px;
            }

            .inst-checkboxClazz {
              width: auto !important;
              margin-bottom: 2px;
            }

            .el-checkbox__label {
              padding-left: 5px;
            }
          }

          .el-radio-group .check-row-inline {
            height: 10px;
            line-height: 30px;
            padding: 0 5px 0 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;

            .el-radio {
              width: 70px !important;
              margin-bottom: 2px;
            }

            .inst-checkboxClazz {
              width: auto !important;
              margin-bottom: 2px;
            }

            .el-radio__label {
              padding-left: 5px;
            }
          }
        }
      }

      .footerBtn {
        height: 32px;
        background-color: $base-white;
      }
    }
  }
}

:deep(.el-dialog) {
  padding: 0;

  .el-dialog__header {
    padding: 15px;
  }

  .el-dialog__body {
    padding: 0;

    .dialog-footer {
      margin: 10px;
      height: 32px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
